<?php

namespace app\modules\Product\controllers;

use Yii;
use app\modules\Product\models\Product;
use app\modules\Product\models\ProductSearch;
use app\modules\Product\models\ProductLog;
use app\modules\Basic\models\CityCode;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\filters\AccessControl;

/**
 * 团队管理
 */
class ProductController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    //团队列表
    public function actionIndex()
    {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $user_id = \yii::$app->user->id;
        $query = Product::find();
        //获取所有客户
        $customer = [];
        $customer_model = $query->Where(['user_id'=>$user_id])->all();
        if($customer_model){
            foreach($customer_model as $cm){
                $customer[$cm->customer_id] = $cm->customer->name;
            }
        }   

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'customer' => $customer,
        ]);
    }

    //修改团队信息
    public function actionEdit(){
        
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = yii::$app->request->get(); 


        if(isset($data['Product']['id'])){

             $model = Product::findOne($data['Product']['id']);

             $model->load($data);

             if($model->save(false)){

                return ['output'=>"", 'message'=>"" ];

             }else{

                return ['output'=>"", 'message'=>"修改失败" ];
             }

        }
    }

    //修改团队状态
    public function actionEditStatus(){
        
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = yii::$app->request->get(); 


        if(isset($data['Product']['id'])){

             $model = Product::findOne($data['Product']['id']);

             $model->load($data);

             if($model->save(false)){

                return ['output'=>Yii::$app->params['product_status'][$model->status], 'message'=>"" ];

             }else{

                return ['output'=>"", 'message'=>"修改失败" ];
             }

        }
    }

    //修改团队类别
    public function actionEditType(){
        
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = yii::$app->request->get(); 


        if(isset($data['Product']['id'])){

             $model = Product::findOne($data['Product']['id']);

             $model->load($data);

             if($model->save(false)){

                return ['output'=>Yii::$app->params['product_type'][$model->product_type], 'message'=>"" ];

             }else{

                return ['output'=>"", 'message'=>"修改失败" ];
             }

        }
    }
     //修改团队信息
    public function actionEditCity(){
        
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = yii::$app->request->get(); 


        if(isset($data['Product']['id'])){

             $model = Product::findOne($data['Product']['id']);

             $model->load($data);

             $model->city = json_encode($model->city);
             
             if($model->save(false)){

                return ['output'=>$model->cityInfo, 'message'=>"" ];

             }else{

                return ['output'=>"", 'message'=>"修改失败" ];
             }

        }
    }

     //指定操作
    public function actionEditOper(){
        
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = yii::$app->request->get(); 


        if(isset($data['Product']['id'])){

             $model = Product::findOne($data['Product']['id']);

             $model->load($data);

             $model->oper_id = json_encode($model->oper_id);
             
             if($model->save(false)){

                return ['output'=>$model->operName, 'message'=>"" ];

             }else{

                return ['output'=>"", 'message'=>"修改失败" ];
             }

        }
    }

    //查看团队
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    //关团
    public function actionClose($id){

       
        $user_id = \yii::$app->user->id;

        $model = $this->findModel($id);

        if($model->user_id != $user_id){
            throw new NotFoundHttpException(Yii::t('app', '没有关团权限'));
            return false;
        }
        $model->status = 10;

        $model->save();

        return $this->redirect(Yii::$app->request->getReferrer());
        
    }

    //删除
    public function actionDel($id){

       
        $user_id = \yii::$app->user->id;

        $model = $this->findModel($id);

        if($model->user_id != $user_id){
            throw new NotFoundHttpException(Yii::t('app', '没有删除权限'));
            return false;
        }
        $model->status = 20;

        $model->save();

        return $this->redirect(Yii::$app->request->getReferrer());
        
    }
   

    //创建团队
    public function actionCreate()
    {
        $model = new Product();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);
        }

        $model->product_type = 1;

        return $this->render('create', [
            'model' => $model,
        ]);
    }


    //上传报价单
    public function actionUploadFile()
    {

        $data = $this->upload_excel();
        
        if($data){
            $res_excel = $this->getData($data['path']);

            $params = yii::$app->request->post();

            $product_id = $params['product_id'];

            $model = Product::findOne($product_id);

            if(empty($model)){
                print_r(json_encode(['code'=>'error','message'=>'没有团队']));
                return false;
            }

            $transaction = Yii::$app->db->beginTransaction();

            try{

                if($model->logNum < 1){ //第一次上传

                    $model->name = $res_excel['product_name'];
                    $model->num = $res_excel['product_num'];
                    $model->begin_date = $res_excel['begin_date'];
                    $model->end_date = $res_excel['end_date'];
                    $model->price = $res_excel['price'];

                    //$model->city = $res_excel['city']; //目的地

                    $city_arr = [];
                    if($res_excel['city']){
                        $citys = explode('+',$res_excel['city']);
                        foreach($citys as $key=>$c){
                            $city_model = CityCode::find()->where(['zh_name'=>$c])->one();
                            if($city_model){
                                $city_arr[$key] = $city_model->code;
                            }
                        }
                    }
                    $first_city = '';
                    if($city_arr){
                        $first_city = $city_arr[0];
                        $model->city = json_encode($city_arr);
                    }
                    $day_date = '';
                    if($res_excel['begin_date']){
                        $day_date = date("ymd",strtotime($res_excel['begin_date']));
                    }

                    $model->code = sprintf('CAD-%s-%s%s',$first_city,$day_date,Yii::$app->user->identity->code);

                }else{

                    $model->price = $res_excel['price'];
                }
            
                if($model->save()){

                    $log = new ProductLog();
                    $log->product_id = $model->id;
                    $log->file_path = $data['path'];
                    $log->name = $data['name'];
                    $log->ext = $data['ext'];
                    $log->size = $data['size'];
                    $log->price = $model->price;

                    if($log->save()){
                        $transaction->commit();
                        print_r(json_encode(['code'=>'ok','message'=>'上传成功！']));
                        return false;
                    }else{
                        $transaction->rollBack();
                        print_r($log->errors);
                        print_r(json_encode(['code'=>'error','message'=>'上传失败3']));
                        return false;
                    }

                }else{
                    $transaction->rollBack();
                    print_r(json_encode(['code'=>'error','message'=>'上传失败2']));
                    return false;
                }

            }catch(\Exception $e){
                $transaction->rollBack();
                throw $e;
            }


        }else{
            print_r(json_encode(['code'=>'error','message'=>'上传失败1']));
        }
        
                

    }

    //上传报价单文件
    private function upload_excel(){

        $upload = UploadedFile::getInstanceByName('excel');
        if($upload){

            $suffix = $upload->extension; //文件后缀
            $name = $upload->name; //文件名
            $size = $upload->size; //文件大小

            if(!in_array($suffix,['xls','xlsx'])){
                print_r(json_encode(['code'=>'error','message'=>'文件不是EXCEL！']));
                return false;
            }
            $dir = sprintf("uploads/product/%s", date("Ym"));
             
            if(!is_readable($dir)) {
                is_file($dir) or mkdir($dir,0755);  
            }  

            $path = sprintf('%s/%s.%s', $dir, uniqid(true), $suffix);

            if($upload->saveAs($path)){
                $data = ['path'=>$path,'name'=>$name,'ext'=>$suffix,'size'=>(string)$size];
                return $data;
            }
        }else{
            return false;
        }

    }

    //解析报价单数据
    private function getData($filePath){

        if(empty($filePath)){
            return [];
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }
        if(!$PHPReader->canRead($filePath)){
            return ;
        }
        $PHPExcel = $PHPReader->load($filePath);

        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet(0);

        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();

        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
          
        $price = 0;  //总价
        $product_name = '';//团组名称;
        $product_num = 0; //会议人数;
        $begin_date = ''; //出发时间
        $end_date = ''; //返回时间
        $city = ''; //目的地

        $product_name = $currentSheet->getCell('B2')->getValue();
        $product_num = $currentSheet->getCell('B4')->getValue();
        //$begin_date = gmdate('Y-m-d',\PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell('B5')->getValue()));
        $begin_date = gmdate('Y-m-d',\PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell('B5')->getCalculatedValue()));
        //$end_date = gmdate('Y-m-d',\PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell('B6')->getValue()));
        $end_date = gmdate('Y-m-d',\PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell('B6')->getCalculatedValue()));
        $city = $currentSheet->getCell('B7')->getValue();

        for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){
            $colIndex = 'A';
            $addr = $colIndex.$rowIndex;
            $cell = $currentSheet->getCell($addr)->getValue();
            if($cell instanceof PHPExcel_RichText){     //富文本转换字符串
                $cell = $cell->__toString();
            }
            $str = '';
            if(!empty($cell)){
                $str = str_replace(' ', '', $cell);
            }
            
            if($str == '总计'){
                //获取报价
                $addr_2 = 'I'.$rowIndex;
                $cell_2 = $currentSheet->getCell($addr_2)->getCalculatedValue();
                if($cell_2 instanceof PHPExcel_RichText){     //富文本转换字符串
                    $cell_2 = $cell_2->__toString();
                }
                $price = $cell_2;
            }
        }

        $res = [
            'product_name' => (string) $product_name,
            'product_num' => (int) $product_num,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'city' => $city,
            'price' => $price,
        ];
        return $res;
    }
   


    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
}
